const { parentPort } = require('worker_threads');
const { WechatyBuilder } = require('wechaty');
const { FileBox } = require('file-box');
const qrcode = require('qrcode-terminal');
const path = require('path');
const fs = require('fs').promises;

class WechatyBot {
    bot = null;
    constructor() {
        this.bot = WechatyBuilder.build();
        this.bot
            .on('scan', code => {
                qrcode.generate(code, { small: true });
                parentPort.postMessage({ type: 'status', code: 0, message: `Scan QR Code: ${code}` });
            })
            .on('login', user => {
                console.log(`User ${user} logged in`);
                parentPort.postMessage({ type: 'status', code: 100, message: 'Bot online' });
            })
            .on('ready', () => {
                console.log('Bot is ready.');
                parentPort.postMessage({ type: 'status', code: 101, message: 'Bot ready.' });
            })
            .on('message', this.handleMessage.bind(this))                   // 监听消息
            .start()
            .then(() => {
                console.log('Bot started.');
                parentPort.postMessage({ type: 'status', code: 201, message: 'Bot started.' });
            })
            .catch(e => {
                console.error(e);
                parentPort.postMessage({ type: 'error', code: 501, message: `Error: ${e}` });
            });
    }

    async getGroupMembers(roomName) {
        const room = await this.bot.Room.find({ topic: roomName });
        if (!room) {
            return 'Room not found';
        }

        const memberList = await room.memberList();
        const members = memberList.map((member, index) => `${index + 1}. ${member.name()}`).join('\n');
        return members;
    }

    // 监听消息函数
    async handleMessage(message) {
        if (message.room()) {
            const room = message.room();
            if (room.payload && room.payload.topic === "机器人日志") {
                if (message.payload.type === 7) {
                    console.log("收到群消息 ==> ", message.text());
                    const content = String(message.text());
                    if (content.split("-")[0] === "获取群用户列表") {
                        const result = await this.getGroupMembers(content.split("-")[1]);
                        room.say(`${content.split("-")[1]} - 查询的结果为：\n${result}`);
                        parentPort.postMessage({ type: 'status', message: `Group members fetched for ${content.split("-")[1]}` });
                    }
                }
            }
        }
    }
}

const bot = new WechatyBot();